#include "../includes.h"

#define MAX_CMD_NO 30

typedef struct{
        char *CmdStr;
	int (*func)(int argc, char **argv);
        char *Help;
} TCommand;



int Help(int argc, char **argv);
int cmd_fpgar(int argc, char **argv);
int cmd_fpgaw(int argc, char **argv);
int cmd_set4G(int argc, char **argv);
int cmd_config(int argc, char **argv);
int cmd_ResetPHY(int argc, char **argv);
int cmd_ResetRCV(int argc, char **argv);
int cmd_Nmea(int argc, char **argv);
int cmd_SelTp(int argc, char **argv);
int cmd_SetUser(int argc, char **argv);
int cmd_UdpTest(int argc, char **argv);
int cmd_UdpAlarm(int argc, char **argv);
int cmd_SetTempGain(int argc, char **argv);
int cmd_PHY(int argc, char **argv);
int cmd_SetAlarmRange(int argc, char **argv);
int cmd_QueryStatus(int argc, char **argv);
int cmd_UserTest(int argc, char **argv);
int cmd_SetPos(int argc, char **argv);
int cmd_SetSystem_Delay(int argc, char **argv);
int cmd_SetFPGA_Change(int argc, char **argv);
int cmd_VME(int argc, char **argv);
int cmd_TOD(int argc, char **argv);
int cmd_NETSEND(int argc, char **argv);
int cmd_GAIN_Change(int argc, char **argv);
int cmd_DAC_Change(int argc, char **argv);
int cmd_OEMV1(int argc, char **argv);
int cmd_OEMV2(int argc, char **argv);
int cmd_RB_SRO100(int argc, char **argv);
//(int argc, char **argv);


TCommand Cmds[MAX_CMD_NO] = {
        { "HLP"		, Help,			"Help"},
        { "FPGAR"		, cmd_fpgar,		"fpgar addr : read value of fpga addr"},
        { "FPGAW"		, cmd_fpgaw,		"fpgar addr data: write value to fpga addr"},
        { "CONFIG"		, cmd_config,		"Set extra config.  \"eg. config rcvType 0/1/2 <-- 0:f1000c, 1:sync15 2:ublox\""},
        { "RSTPHY"		, cmd_ResetPHY,		"Assert reset signal to PHY"},
        { "PHY"			, cmd_PHY,			"PHY GET xxx"},
        { "RSTRCV"		, cmd_ResetRCV,		"Assert reset signal to GPS Receiver"},
        { "NMEA"		, cmd_Nmea,			"Send Nmea command to GPS Receiver(only to f1000c)"},
        { "SELTP"		, cmd_SelTp,		"Select 1PPS TP 0:1PPS, 1:eb 1pps"},
        { "SETUSR"		, cmd_SetUser,		"Do not use!!.. reserved for GUI Interface"},
        { "SETRANGE"	, cmd_SetAlarmRange,"Set Alarm Range for validation eg.) SetRange ON/OFF"},
        { "UDPTST"		, cmd_UdpTest,		"Do not Use "},
        { "USERTEST"	, cmd_UserTest,		"Do not Use "},
        { "QUERYSTATUS"	, cmd_QueryStatus,	"For GUI Interface"},
        { "SETPOS"	, cmd_SetPos,	"Change ECEF Position of Ant."},
        { "SYSDELAY"	, cmd_SetSystem_Delay,	"Change SYSTEM_DELAY.\n \t\tex)sysdelay number[unit : 100ns]"},
        { "FPGACH"	, cmd_SetFPGA_Change,	"Change FPGAData Mode.\n \t\tex)fpgach [value 0:FPGAData.h, 1:cnt.bin]"},
        { "VME"		, cmd_VME,	"Change VME Mode.\n \t\tex)vme mode [value] [value 0:Master, 1:Slave]"},
        { "TOD"		, cmd_TOD,	"Change TOD MUX.\n \t\tex)TOD MUX0  [0~3]"},
        { "NETSEND"		, cmd_NETSEND,	"Change NETSEND Mode.\n \t\tex)NETSEND [value] [value 0:BlockRam Send, 1:NETSEND]"},
        { "GAIN"		, cmd_GAIN_Change,	"Change GAIN Change.\n \t\tex)GAIN 5.12   [E-13]"},
        { "DAC"		, cmd_DAC_Change,		"Change DAC Change.\n \t\tex)DAC 32767"},
        { "OEMV1"		, cmd_OEMV1,	"OEMV1 Command Send\n"
        		"\t\t ex) oemv1 [oemv1 Command]\n"
        		"\t\t ex) oemv1 log rangea ontime 1\t{oemv1 command send}\n"
        		"\t\t ex) oemv1 print\t\t{oemv1 receive data print}\n"
        		"\t\t\tone more typing-->No print\n"
        		"\t\t ex) oemv1 com com1 115200\t{oemv1 baud_rate Change}"},
        { "OEMV2"	, cmd_OEMV2,	"OEMV2 Command Send\n"
        		"\t\t ex) oemv2 [oemv2 Command]\n"
        		"\t\t ex) oemv2 log rangea ontime 1\t{oemv2 command send}\n"
        		"\t\t ex) oemv2 print\t\t{oemv2 receive data print}\n"
        		"\t\t\tone more typing-->No print\n"
        		"\t\t ex) oemv2 com com1 115200\t{oemv2 baud_rate Change}"},
        { "RB"	, cmd_RB_SRO100,	"Rubidium Command Send\n"
        	   "\t\t ex) rb [rb Command]\n"
        	   "\t\t ex) rb print\t\t{Rubidium receive data print}\n"
        	   "\t\t\tone more typing-->No print\n"
        	   "\t\t ex) rb baud 115200\t{Rubidum baud_rate Change}"},
        { "SETTGAIN"	, cmd_SetTempGain,
				"eg. setTgain disp/calc/init/set xxx\n"
        		"\t\t DISP:Display table , CALC: caculation & apply, INIT: table clear\n"
				"\t\t Set xxx <-- temp. gain. 203 means 2.03 dac value/1 degree celsius\n"
        },
        { "ERROR"		, cmd_UdpAlarm,		"force rcu-g to intensional error condition,\n"
				"\t\t example)\n"
        		"\t\t ------alarm---------------\n"
				"\t\t error ant  open/short/off \n"
				"\t\t error efc  on/off \n"
				"\t\t error ocxo on/off \n"
				"\t\t error holdover warn1/warn2/off \n"
        		"\t\t ------aux.-----------------\n"
				"\t\t error gps  on/off  --> for holdover\n"
				"\t\t error range on/off --> on: ignore period range chack\n"
        		"\t\t ---------------------------\n"
        },
        { NULL			, NULL,			NULL}
};

int bFirstQueryStatus=1;
int cmd_QueryStatus(int argc, char **argv)
{
	st_alarm v= buf_alm.value.b;
	KTI_SubData_Report_T *p=&buf_report;
	char buf[3][100];
	int8u mac[6];
	if(bFirstQueryStatus || mac_str[0]==0 ){ bFirstQueryStatus=0; GetIPconfig(ip_cfg_MAC ,mac); }
	printf("$QUERYSTATUS");
	printf(",ver,%s,%s,%s",FirmWare_Version ,GetMasterID() ,GetSerialNumber() );
	printf(",alm,%d,%d,%d,%d,%d,%d"
			,v.ocxo_fault, v.clk_na, v.ant_open, v.ant_short, v.gps_holdover, v.ocxo_efc );
	printf(",tv,%d,%d,%d",p->time_valid ,p->running_sec ,p->holdover_sec);

	if(p->status<3) printf(",st,%d,%+2.1e,%d",p->status,CONTROL.Frequency,p->dac );
	else printf(",st,%d,Holdover,%d",p->status,p->dac );

	printf(",v,%d,%d,%d,%d"
		   ",ss,%d,%d,%d,%d"
			,(int)p->gps_visible, (int)p->gps_tracking, (int)p->RcvComm, (int)p->gps_ant
			, (int)p->gps_cn_min, (int)p->gps_cn_mean, (int)p->gps_cn_max, (int)p->temperature);
	printf(",period,%d,%d,%s"
			,CONFIG.iPeriodUdpReport , CONFIG.iPeriodHeartBeat, mac_str );
	printf(",*\n");
	return 1;
}

//typedef struct
//{
//	int holdover_warn1; //86400*7
//	int holdover_warn2;	//86400*14
//	int ant_fault;		//3600
//}stAlarmRange_;

stAlarmRange_ alm_range = { 86400*7, 86400*28,  60*60 };

int cmd_SetAlarmRange(int argc, char **argv)
{
	if( argc == 2 )
	{
		if( strcmp( argv[1], "ON" ) == 0 )
		{
			alm_range.holdover_warn1 = 60*5;
			alm_range.holdover_warn2 = 60*10;
			alm_range.ant_fault = 2*60;
		}
		if( strcmp( argv[1], "OFF" ) == 0 )
		{
			alm_range.holdover_warn1 = 86400*7;
			alm_range.holdover_warn2 = 86400*28;
			alm_range.ant_fault = 60*60;
		}
	}

	printf("\nAlarm Range\n"
			"holdover warn1:%d\n"
			"holdover warn2:%d\n"
			"ant fault:%d\n"
			,alm_range.holdover_warn1
			,alm_range.holdover_warn2
			,alm_range.ant_fault
	);
	return 1;
}

IntensionalStatus_ frc_error ={0,0,0,0,0  ,0};

int cmd_UdpAlarm(int argc, char **argv)
{
	int result=-1;
	if( argc < 3 ){ printf("error: argc:%d \n",argc); return 0; }
	if( strcmp( argv[1], "GPS" ) == 0 )
	{
		if( strcmp( argv[2], "ON" ) == 0  ) frc_error.gps = 1;
		if( strcmp( argv[2], "OFF" ) == 0 ) frc_error.gps = 0;
		result = frc_error.gps;
	}
	else
	if( strcmp( argv[1], "RANGE" ) == 0 )
	{
		if( strcmp( argv[2], "OFF"   ) == 0 ) frc_error.inore_range = 0;
		if( strcmp( argv[2], "ON"    ) == 0 ) frc_error.inore_range = 1;
		result = frc_error.inore_range ;
	}
	else
	if( strcmp( argv[1], "ANT" ) == 0 )
	{
		if( strcmp( argv[2], "OFF"   ) == 0 ) frc_error.ant = 0;
		if( strcmp( argv[2], "OPEN"  ) == 0 ) frc_error.ant = 1;
		if( strcmp( argv[2], "SHORT" ) == 0 ) frc_error.ant = 2;
		result = frc_error.ant ;
	}
	else
	if( strcmp( argv[1], "EFC" ) == 0 )
	{
		if( strcmp( argv[2], "OFF" ) == 0 ) frc_error.efc = 0;
		if( strcmp( argv[2], "ON"  ) == 0 ) frc_error.efc = 1;
		result = frc_error.efc ;
	}
	else
	if( strcmp( argv[1], "OCXO" ) == 0 )
	{
		if( strcmp( argv[2], "OFF" ) == 0 ) frc_error.ocxo = 0;
		if( strcmp( argv[2], "ON"  ) == 0 ) frc_error.ocxo = 1;
		result = frc_error.ocxo ;
	}
	else
	if( strcmp( argv[1], "HOLDOVER" ) == 0 )
	{
		if( strcmp( argv[2], "OFF"  ) == 0  ) frc_error.holdover = 0;
		if( strcmp( argv[2], "WARN1" ) == 0 ) frc_error.holdover = 1;
		if( strcmp( argv[2], "WARN2" ) == 0 ) frc_error.holdover = 2;
		result = frc_error.holdover ;
	}

	printf("%s-->%d \n",argv[1], result);
	return 1;
}


char *delimit = " \n\r";
char *argv[16];

int i_cmd_ResetRCV=0;
int i_cmd_ResetRCVLimit=3;

int b_RstF1000c=0;
int i_RstF1000c=0;

void task_cmd()
{
	//GetGainTask
	if( st_gg.running ){
		GetOCXOGain();
	}

	///// Receiver Reset task
	if( i_cmd_ResetRCV !=0 ){ // reset gps receiver for a while
	  if( i_cmd_ResetRCV++ > i_cmd_ResetRCVLimit){
		SetBitLow(12,wbD6);
		i_cmd_ResetRCV = 0;
		printf("\n End \n");
	  }
	  else{
		  if( i_cmd_ResetRCV == 1) printf("\n Reset GPS Receiver \n");
		  SetBitHigh(12,wbD6);
	  }
	}

	if( b_RstF1000c ){
	  switch( i_RstF1000c ){
		  case 0:
			  //SendCommandToF1000c(nmeaResetAll);
			  printf("Set Rcv cold\n");
			  i_RstF1000c++;
			  break;

		  case 1:
			  SetBitHigh(12,wbD6);
			  printf("Rst Rcv High \n");
			  i_RstF1000c++;
			  break;

		  case 2:
			  SetBitLow(12,wbD6);
			  printf("Rst Rcv Low \n");
			  b_RstF1000c=0;
			  i_RstF1000c=0;
			  break;
		  default:
			  b_RstF1000c=0;
			  i_RstF1000c=0;
			  break;
	  }

	}
}


int Parse_Args(char *cmdline, char **argv)
{
	char *tok;
	int argc = 0;

	argv[argc] = NULL;

	//for(tok = strtok(cmdline, delimit); tok && argc<16; tok = strtok(NULL, delimit))
	for(tok = strtok(cmdline, delimit); tok && argc<16; tok = strtok(NULL, delimit))
    	{
		argv[argc++] = tok;
	}

	return argc;
}

int Help(int argc, char **argv)
{
	int i;
	//PutStrN("\r\nHelp\r\n");
	dbg_printf("\n\n------------------ Help ------------------\n");
	for( i=1; Cmds[i].Help != NULL && i <MAX_CMD_NO; i++)
	{
		//printf("Help:%2d> %s %s\n",i,Cmds[i].CmdStr,Cmds[i].Help);
		dbg_printf("%2d ) %s \t> %s\n",i,Cmds[i].CmdStr,Cmds[i].Help);

	}
	if( argc > 1 ){
		dbg_printf("argv: %d\n", (int)strtoul(argv[1],NULL,0) );
	}

	dbg_printf("------------------------------------------\n");
	return 1;
}

int cmd_SetTempGain(int argc, char **argv)
{

	if( argc > 1){
		if( strcmp(argv[1],"DISP")==0 ){
			bTGainDisply = 1;
		}
		else if( strcmp(argv[1],"CALC")==0 ){
			TGainCalc(1);
		}
		else if( strcmp(argv[1],"INIT")==0 ){
			TempGain.first = 1;
			TempGain.i=0; TempGain.cnt=0;
		}
		else if( strcmp(argv[1],"SET")==0 ){
			if(argc>2){
				CONFIG.iTemperatureGain = (double)strtoul(argv[1],NULL,0);
				CONFIG.WriteEvent = ON;
			}
		}

	}
//	else if( argc > 1){
//		CONFIG.iTemperatureGain = (double)strtoul(argv[1],NULL,0);
//		CONFIG.WriteEvent = ON;
//	}
	printf("temperature gain: %d e-100\n",(int)CONFIG.iTemperatureGain);
	return 1;
}

int cmd_SetPos(int argc, char **argv)
{
	int id;
	if( argc == 4 ){
		CONFIG.PosX  = my_atof(argv[1]);
		CONFIG.PosY  = my_atof(argv[2]);
		CONFIG.PosZ  = my_atof(argv[3]);
		printf("\r\npos:%f, %f, %f\r\n",CONFIG.PosX,CONFIG.PosY,CONFIG.PosZ);

		CONFIG.WriteEvent = ON;

		sprintf(MESG,"#RCUPOS,%f,%f,%f*xxx\r\n",CONFIG.PosX,CONFIG.PosY,CONFIG.PosZ);		//sewon
		oemv3_msg_rcvd( MESG, 0, strlen(MESG), SDATA, fdEB);
	}
	else{
		printf("usage: SetPos x,y,z\n");
		printf("\r\npos(%d):%f, %f, %f\r\n",CONFIG.iCVType,CONFIG.PosX,CONFIG.PosY,CONFIG.PosZ);
		id =0; printf("\r\npos:%d:%f, %f, %f\r\n",id,myObs[id].pos[0],myObs[id].pos[1],myObs[id].pos[2]);
		id =1; printf("\r\npos:%d:%f, %f, %f\r\n",id,myObs[id].pos[0],myObs[id].pos[1],myObs[id].pos[2]);
	}
	return 1;
}

int cmd_SetSystem_Delay(int argc, char **argv)
{
	if( argc == 2 ){
		CONFIG.SYSTEM_DELAY  = my_atof(argv[1]);
		printf("\r\nSYSTEM_DELAY : %f ns\r\n",CONFIG.SYSTEM_DELAY);
		CONFIG.WriteEvent = ON;
	}
	else{
		printf("usage: SYSTEM_DELAY\n");
		printf("\r\nGain(%d):%f ns\r\n",CONFIG.iCVType,CONFIG.SYSTEM_DELAY);
		//id =0; printf("\r\npos:%d:%f, %f, %f\r\n",id,myObs[id].pos[0],myObs[id].pos[1],myObs[id].pos[2]);
		//id =1; printf("\r\npos:%d:%f, %f, %f\r\n",id,myObs[id].pos[0],myObs[id].pos[1],myObs[id].pos[2]);
	}
	return 1;
}

int cmd_SetFPGA_Change(int argc, char **argv){
	unsigned int v;
	if( argc == 2 ){
		v = strtoul(argv[1],NULL,0);
		if( v == 0 || v == 1 ){
			Initialization();
			CONFIG.FPGACH  = my_atof(argv[1]);
			if(v==0)	CONFIG.VMEMODE = 1;
			else		CONFIG.VMEMODE = 0;
			printf("FPGACH : %s \r\n",(CONFIG.FPGACH==0)?"VME_Slave!":"VME_Master!");
			CONFIG.WriteEvent = ON;
			fpga_init(fdFPGA);
		}
		else{
			printf("ERROR!!>FPGACH Value only 0 or 1\n");
			return 1;
		}
	}
	else{
		printf("0:VME_Slave, 1:VME_Master\tex)fpgach 0  ex)fpgach 1   \n");
		printf("Current FPGACH Value : %s\r\n",(CONFIG.FPGACH==0)?"VME_Slave":"VME_Master");
	}
	return 1;
}
#define TTT 3*1024
#define UUU 4*1024
unsigned char test_buff[TTT];
unsigned char test_buff2[UUU];
int cmd_VME(int argc, char **argv)	//12-05-09	sewon
{
	int i;
	int vme_test_addr=0x1000;
	unsigned int v;
	int addr,data=0;
	int temp;
	int test_value=0xc02200;
	int CV_START_ADDR = VME_CV_START_ADDR__;
	int size;
	FILE* ffp;
	_CV_Data *CV = &VME.CV_Data;

	if( argc > 1)
	{
		if( argc == 2 ){
			v = strtoul(argv[1],NULL,0);
			if( strcmp(argv[1],"CVNOTSEND") == 0 ){
				VME.CV_Data.CV_Data_Disable	^=	ON;
				if( VME.CV_Data.CV_Data_Disable==ON )	printf("CV Data Send Stop!\n");
				else									printf("CV Data Send Start!\n");
			}

			if( strcmp(argv[1],"CVREAD") == 0 ){

				printf("###CVREAD###\n");

				ffp=fopen("/gpsclock/ORG/PopCVData","a+");
				if( ffp == NULL ){
					printf( "Open Error... /gpsclock/ORG/PopCVData... for write+\n");
					//LogItString (LOG_CATA1_NORM, LOG_CATA2_FAIL, "File open for write");
					exit(-1);
				}

				if (CONFIG.VMEMODE == 0)
					size = VME_Read(VME_ADDR_CV);
				else
					size = VME_BlockRam_Read(VME_ADDR_CV);
				size = 11000;
				fprintf(ffp,"%s","\n###CVREAD###\n");
					for (i = 0; i < size; i += 2, CV_START_ADDR += 2) {
						if (CONFIG.VMEMODE == 0){
							temp = VME_Read(CV_START_ADDR);
							fprintf(ffp,"%c%c", ((temp>>8)&0xFF), (temp&0xFF));
						}
						else{
							temp = VME_BlockRam_Read(CV_START_ADDR);
							fprintf(ffp,"%c%c", ((temp>>8)&0xFF), (temp&0xFF));
						}
					}
				fprintf(ffp,"%s","\n<<====[Stop!]====>>\n");

			}

			if( strcmp(argv[1],"INIT") == 0 ){
				printf("Initialization() \n");
				Initialization();
			}
			if( strcmp(argv[1],"CONTROLINIT") == 0 ){
				printf("Init_CONTROL() \n");
				Init_CONTROL();
			}
			if( strcmp(argv[1],"KALMANINIT") == 0 ){
				printf("InitializeKalmanControl() \n");
				InitializeKalmanControl();
			}
			if( strcmp(argv[1],"RESET") == 0 ){
			}
			if( strcmp(argv[1],"TEST0") == 0 ){
				printf("TEST0\n");
				CONTROL.IntervalCounter = 0;
			}
			if( strcmp(argv[1],"TEST1") == 0 ){
				printf("TEST1\n");
				CONTROL.IntervalCounter = 1;
			}
			if( strcmp(argv[1],"TEST5") == 0 ){
				printf("TEST5\n");
				CONTROL.IntervalCounter = 5;
			}


			if( strcmp(argv[1],"HELP") == 0 ){
				printf("\n======Debug Help======\n"
						"***Update BlockRam***\n"
						"\t- Update Data\t\t3360\n"
						"\t- Read Mode\t\t3361\n\n"
						"***VME Master***\n"
						"\t- VME Write\t\t3363\n"
						"\t- VME Read\t\t3364\n\n"
						"***VME Slave***\n"
						"\t- CV Write\t\t3370\n"
						"\t- CV Read\t\t3369\n"
						"***TOD Print***\n"
						"\t- TOD Print\t\t3366\n"
						"======================\n");
			}

		}
		if( argc == 3 ){
			v = strtoul(argv[2],NULL,0);
			if( strcmp(argv[1],"MODE") == 0)
			{
				if( v == 0 || v == 1 ){
					CONFIG.VMEMODE  = v;
					printf("VMEMODE : %s \r\n",(CONFIG.VMEMODE==0)?"Master":"Slave");
					CONFIG.WriteEvent = ON;
				}
				else{
					printf("ERROR!!>VMEMODE Value only 0 or 1\n");
					return 1;
				}
			}
			else if( strcmp(argv[1],"READ") == 0 ){
				if( CONFIG.VMEMODE == 1 ){
					printf("Not Master Mode!\n");
					return 1;
				}
				addr=data=0;
				addr = strtoul(argv[2],NULL,0);
				data = VME_Read(addr);
				printf("VME Read>> 0x%08X( %d ) : 0x%08X( %d )\n",addr,addr,data,data);
			}
			else if( strcmp(argv[1],"SLAVE") == 0 ){
				if( CONFIG.VMEMODE == 0 ){
					printf("Not Slave Mode\n");
					return 1;
				}
				if( strcmp(argv[2],"DATADIR") == 0 ){
					DATA_DIR();
					printf("1PPS_Port->DATA_DIR\n");
				}
				else if( strcmp(argv[2],"DTACK") == 0 ){
					DTACK();
					printf("1PPS_Port->DTACK\n");
				}
				else if( strcmp(argv[2],"WRITEEN") == 0 ){
					WRITE_EN();
					printf("1PPS_Port->WRITE_EN\n");
				}
				else if( strcmp(argv[2],"READEN") == 0 ){
					READ_EN();
					printf("1PPS_Port->READ_EN\n");
				}
			}
		}
		if( argc == 4 ){
			if( strcmp(argv[1],"WRITE") == 0 ){
				if( CONFIG.VMEMODE == 1 ){
					printf("Not Master Mode!\n");
					return 1;
				}
				addr=data=0;
				addr = strtoul(argv[2],NULL,0);
				data = strtoul(argv[3],NULL,0);
				VME_Write(addr,data);
				printf("VME Write>> 0x%08X( %d ) : 0x%08X( %d )\n",addr,addr,data,data);
			}
			else if( strcmp(argv[1],"SLAVE") == 0 ){
				if( strcmp(argv[2],"MUX") == 0 ){
					if( CONFIG.VMEMODE == 0 ){
						printf("Not Slave Mode!\n");
						return 1;
					}
					v = strtoul(argv[3],NULL,0);
					if(v==0){
						VME_MUX_AS();
						printf("VME_MUX_AS();\n");
					}
					else if(v==1){
						VME_MUX_DS1();
						printf("VME_MUX_DS1();\n");
					}
					else if(v==2){
						VME_MUX_CLK();
						printf("VME_MUX_CLK();\n");
					}
					else if(v==3){
						VME_MUX_LWORD();
						printf("VME_MUX_LWORD();\n");
					}
					else if(v==4){
						VME_MUX_IACK();
						printf("VME_MUX_IACK();\n");
					}
					else if(v==5){
						VME_MUX_WR();
						printf("VME_MUX_WR();\n");
					}
					else if(v==6){
						VME_MUX_IRQ6_REQ();
						printf("VME_MUX_IRQ6_REQ();\n");
					}
					else if(v==7){
						VME_MUX_BIT_MODE();
						printf("VME_MUX_BIT_MODE();\n");
					}
				}
			}
		}

		//BlockRam Test
		if( strcmp(argv[1],"BLOCKWR") == 0 ){
			if( CONFIG.VMEMODE == 0 )
			{
				printf("Not VME Slave\n");
				return 1;
			}
			if( argc == 3 ){		//Read
				addr = strtoul(argv[2],NULL,0);
				data = VME_BlockRam_Read(addr);
				printf("VME_BlockRam_A_Read>>0x%02X( %d ) : 0x%02X( %d )\n",addr,addr,data,data);
			}
			else if( argc == 4 ){	//Write
				addr = strtoul(argv[2],NULL,0);
				data = strtoul(argv[3],NULL,0);

				VME_BlockRam_Write(addr,data);
				printf("VME_BlockRam_A_Write>>0x%02X( %d ) : 0x%02X( %d )\n",addr,addr,data,data);
			}
			else{
				printf("ex)Read : VME BLOCKWR [addr]\n"
						"ex)Write : VME BLOCKWR [addr] [data]\n");
			}
		}
	}
	else{
		printf("0:VME Master, 1:VME Slave\tex)vme mode 0  ex)vme mode 1   \n");
		printf("Current VMEMODE Value : %s\r\n",(CONFIG.VMEMODE==0)?"Master":"Slave");
	}
	return 1;
}

int cmd_TOD(int argc, char **argv)	//12-05-09	sewon
{
	int i;
	unsigned int v;
	int addr,data=0;
	if( argc > 1)
	{
		if( argc == 2 ){
			v = strtoul(argv[1],NULL,0);
			if( strcmp(argv[1],"MUX0") == 0 ){
				TOD_MUX_MAIN_1PPS();
			}
			else if( strcmp(argv[1],"MUX1") == 0 ){
				TOD_MUX_ADD_17();
			}
			else if( strcmp(argv[1],"MUX2") == 0 ){
				TOD_MUX_SASC_BRG();
			}
			else if( strcmp(argv[1],"MUX3") == 0 ){
				TOD_MUX_TOD_OUT();
			}
		}
		else{
			printf(" \n");
		}
	}

	return 1;
}
int cmd_NETSEND(int argc, char **argv)	//12-05-29	sewon
{
	unsigned int v;
	if( argc == 2 ){
		v = strtoul(argv[1],NULL,0);

		CONFIG.NETSEND  = my_atoi(argv[1]);
		printf("NETSEND : %d \r\n",CONFIG.NETSEND);
		CONFIG.WriteEvent = ON;
	}
	else{
		printf("NETSEND : %s \r\n",(CONFIG.NETSEND==1)?"NETSEND_Mode":"VMESEND_Mode");
	}
	return 1;
}

int cmd_GAIN_Change(int argc, char **argv)
{
	unsigned int v;
	if( argc == 2 ){
		v = strtoul(argv[1],NULL,0);

		CONFIG.GAIN  = my_atof(argv[1])*1E-13;
		printf("GAIN : %e \r\n",CONFIG.GAIN);
		CONFIG.WriteEvent = ON;
	}
	else{
		printf("GAIN : %e \r\n",CONFIG.GAIN);
	}
	return 1;
}
int cmd_DAC_Change(int argc, char **argv)
{
	unsigned int v;
	if( argc == 2 ){
		v = strtoul(argv[1],NULL,0);

		CONFIG.DAC  = my_atoi(argv[1]);
		printf("DAC : %d \r\n",CONFIG.DAC);
		CONFIG.WriteEvent = ON;
	}
	else{
		printf("DAC : %d \r\n",CONFIG.DAC);
	}
	return 1;
}
int cmd_OEMV1(int argc, char **argv)	//sewon
{
	char buf[MAX_CMD_SIZE];
	char sp=32;		//space
	char *psp=&sp;
	int i;

	if( argc == 2 )
	{
		if( strcmp(argv[1],"PRINT") == 0 )//OEMV Message->Console print
		{
			SYSTEM.EB2.print_Flag ^= ON;
			if( SYSTEM.EB2.print_Flag == ON ) 	printf("OEMV1 Print ON\n");
			else 							  				printf("OEMV1 Print OFF\n");
			return 1;
		}
	}
	else if( argc == 3 )//oemv1 externalclock disable-----can't command
	{
		if( strcmp(argv[1],"EXTERNALCLOCK") == 0 && strcmp(argv[2],"DISABLE") == 0 )
		{
			printf("can't command\nreason : OEMV1 have not ExternalClock\n");
			return 1;
		}
	}
	else if( argc == 4 )//|| argc == 10 )
	{
		if( strcmp(argv[1],"COM") == 0 )
		{
			if( argc == 4 )
			{
				sprintf(buf,"%s %s %s N 8 1 N OFF ON\r\n",argv[1],argv[2],argv[3]);
			}
			else if ( argc == 10 )
			{
				printf("commad error!\tex) oemv1 com com1 115200\n");
				return 1;
				//sprintf(buf,"%s %s %s %s %s %s %s %s %s\r\n",argv[1],argv[2],argv[3],argv[4],argv[5],argv[6],argv[7],argv[8],argv[9]);
			}
			printf("<------OEMV1 Send cmd:%s\n",buf);
			write(fdEB2,buf,strlen(buf));

			if( strcmp(argv[3],"300") == 0 ) set_tty( fdEB2, B300, 2 );
			else if( strcmp(argv[3],"600") == 0 ) set_tty( fdEB2, B600, 2 );
			else if( strcmp(argv[3],"1200") == 0 ) set_tty( fdEB2, B1200, 2 );
			else if( strcmp(argv[3],"2400") == 0 ) set_tty( fdEB2, B2400, 2 );
			else if( strcmp(argv[3],"4800") == 0 ) set_tty( fdEB2, B4800, 2 );
			else if( strcmp(argv[3],"9600") == 0 ) set_tty( fdEB2, B9600, 2 );
			else if( strcmp(argv[3],"19200") == 0 ) set_tty( fdEB2, B19200, 2 );
			else if( strcmp(argv[3],"38400") == 0 ) set_tty( fdEB2, B38400, 2 );
			else if( strcmp(argv[3],"57600") == 0 ) set_tty( fdEB2, B57600, 2 );
			else if( strcmp(argv[3],"115200") == 0 ) set_tty( fdEB2, B115200, 2 );
			else if( strcmp(argv[3],"230400") == 0 ) set_tty( fdEB2, B230400, 2 );
			else if( strcmp(argv[3],"460800") == 0 ) set_tty( fdEB2, B460800, 2 );
			else if( strcmp(argv[3],"921600") == 0 ) set_tty( fdEB2, B921600, 2 );

			printf("set_tty(OEMV1,%s)\n",argv[3]);

			return 1;
		}
	}

	for(i=0;i<MAX_CMD_SIZE;i++)
		buf[i] = 0;

	for(i=1;i<argc;i++)
	{
		strcat(buf,argv[i]);
		if( i == argc-1 )
		{
			buf[strlen(buf)] = '\r';
			buf[strlen(buf)+1] = '\n';
		}
		else
			buf[strlen(buf)] = sp;
	}

	write(fdEB2,buf,strlen(buf));

	printf("<------OEMV1 Send cmd:%s\n",buf);

	return 1;
}

int cmd_OEMV2(int argc, char **argv)	//sewon
{
	char buf[MAX_CMD_SIZE];
	char sp=32;		//space
	char *psp=&sp;
	int i;

	if( argc == 2 )
	{
		if( strcmp(argv[1],"PRINT") == 0 )//OEMV Message->Console print
		{
			SYSTEM.EB.print_Flag ^= ON;
			if( SYSTEM.EB.print_Flag == ON ) 	printf("OEMV2 Print ON\n");
			else 							  				printf("OEMV2 Print OFF\n");
			return 1;
		}
	}
	else if( argc == 4 )//|| argc == 10 )
	{
		if( strcmp(argv[1],"COM") == 0 )
		{
			if( argc == 4 )
			{
				sprintf(buf,"%s %s %s N 8 1 N OFF ON\r\n",argv[1],argv[2],argv[3]);
			}
			else if ( argc == 10 )
			{
				printf("commad error!\tex) oemv2 com com1 115200\n");
				return 1;
				//sprintf(buf,"%s %s %s %s %s %s %s %s %s\r\n",argv[1],argv[2],argv[3],argv[4],argv[5],argv[6],argv[7],argv[8],argv[9]);
			}
			printf("<------OEMV2 Send cmd:%s\n",buf);
			write(fdEB,buf,strlen(buf));

			if( strcmp(argv[3],"300") == 0 ) set_tty( fdEB, B300, 1 );
			else if( strcmp(argv[3],"600") == 0 ) set_tty( fdEB, B600, 1 );
			else if( strcmp(argv[3],"1200") == 0 ) set_tty( fdEB, B1200, 1 );
			else if( strcmp(argv[3],"2400") == 0 ) set_tty( fdEB, B2400, 1 );
			else if( strcmp(argv[3],"4800") == 0 ) set_tty( fdEB, B4800, 1 );
			else if( strcmp(argv[3],"9600") == 0 ) set_tty( fdEB, B9600, 1 );
			else if( strcmp(argv[3],"19200") == 0 ) set_tty( fdEB, B19200, 1 );
			else if( strcmp(argv[3],"38400") == 0 ) set_tty( fdEB, B38400, 1 );
			else if( strcmp(argv[3],"57600") == 0 ) set_tty( fdEB, B57600, 1 );
			else if( strcmp(argv[3],"115200") == 0 ) set_tty( fdEB, B115200, 1 );
			else if( strcmp(argv[3],"230400") == 0 ) set_tty( fdEB, B230400, 1 );
			else if( strcmp(argv[3],"460800") == 0 ) set_tty( fdEB, B460800, 1 );
			else if( strcmp(argv[3],"921600") == 0 ) set_tty( fdEB, B921600, 1 );

			printf("set_tty(OEMV2,%s)\n",argv[3]);

			return 1;
		}
	}

	for(i=0;i<MAX_CMD_SIZE;i++)
		buf[i] = 0;

	for(i=1;i<argc;i++)
	{
		strcat(buf,argv[i]);
		if( i == argc-1 )
		{
			buf[strlen(buf)] = '\r';
			buf[strlen(buf)+1] = '\n';
		}
		else
			buf[strlen(buf)] = sp;
	}

	write(fdEB,buf,strlen(buf));

	printf("<------OEMV2 Send cmd:%s\n",buf);

	return 1;
}

int cmd_RB_SRO100(int argc, char **argv)	//sewon
{
	char buf[MAX_CMD_SIZE];
	char sp=32;		//space
	char *psp=&sp;
	int i;

	if( argc == 2 )
	{
		if( strcmp(argv[1],"PRINT") == 0 )//Rubidium Message->Console print
		{
			rb.sro100.print_Flag ^= ON;
			if( rb.sro100.print_Flag == ON ) 	printf("Rubidum Print ON\n");
			else 							  				printf("Rubidum Print OFF\n");
			return 1;
		}
		if( strcmp(argv[1],"STATUS") == 0 )//Rubidium Status
		{
			printf("\n======Rubidium Status======\n");
			printf("Lock : %d\t(0:not lock, 1:Free Run, 2:Disciplined)\n",rb.sro100.quality);
			printf("PPSREFvsPPSOUT : %.9lf(sec)\n",rb.sro100.time_interval*133E-9);
			printf("Rb_SRO-100 Gain : %01.2e\n",CONFIG.GAIN);
			printf("===========================\n");
			return 1;
		}
	}
	else if( argc == 3 )
	{
		if( strcmp(argv[1],"BAUD") == 0 )
		{
			//sprintf(buf,"%s %s %s %s %s %s %s %s %s\r\n",argv[1],argv[2],argv[3],argv[4],argv[5],argv[6],argv[7],argv[8],argv[9]);

			//printf("<------Rubidium Send cmd:%s\n",buf);
			//write(fdRbSRO,buf,strlen(buf));

			if( strcmp(argv[2],"300") == 0 ) set_tty( fdRbSRO, B300, 0 );
			else if( strcmp(argv[2],"600") == 0 ) set_tty( fdRbSRO, B600, 0 );
			else if( strcmp(argv[2],"1200") == 0 ) set_tty( fdRbSRO, B1200, 0 );
			else if( strcmp(argv[2],"2400") == 0 ) set_tty( fdRbSRO, B2400, 0 );
			else if( strcmp(argv[2],"4800") == 0 ) set_tty( fdRbSRO, B4800, 0 );
			else if( strcmp(argv[2],"9600") == 0 ) set_tty( fdRbSRO, B9600, 0 );
			else if( strcmp(argv[2],"19200") == 0 ) set_tty( fdRbSRO, B19200, 0 );
			else if( strcmp(argv[2],"38400") == 0 ) set_tty( fdRbSRO, B38400, 0 );
			else if( strcmp(argv[2],"57600") == 0 ) set_tty( fdRbSRO, B57600, 0 );
			else if( strcmp(argv[2],"115200") == 0 ) set_tty( fdRbSRO, B115200, 0 );
			else if( strcmp(argv[2],"230400") == 0 ) set_tty( fdRbSRO, B230400, 0 );
			else if( strcmp(argv[2],"460800") == 0 ) set_tty( fdRbSRO, B460800, 0 );
			else if( strcmp(argv[2],"921600") == 0 ) set_tty( fdRbSRO, B921600, 0 );

			printf("set_tty(Rubidum,%s)\n",argv[2]);

			return 1;
		}
	}

	for(i=0;i<MAX_CMD_SIZE;i++)
		buf[i] = 0;

	for(i=1;i<argc;i++)
	{
		strcat(buf,argv[i]);
		if( i == argc-1 )
		{
			buf[strlen(buf)] = '\r';
			buf[strlen(buf)+1] = '\n';
		}
		else
			buf[strlen(buf)] = sp;
	}

	write(fdRbSRO,buf,strlen(buf));

	printf("<------Rubidium Send cmd:%s\n",buf);

	return 1;
}
int cmd_UserTest(int argc, char **argv)
{
	if( argc == 2 ){
		if( !strcmp(argv[1],"LOG") ){
			printf("RCU-G Log...\n");
			bDisplayLog = 1;
		}

		if( !strcmp(argv[1],"GETGAIN") )
		{
			st_gg.running = 1;
			printf("Start GetGain...\n");
		}
		if( !strcmp(argv[1],"GETGAINSTOP") )
		{
			st_gg.step = 0;
			st_gg.running = 0;
			printf("STOP GetGain...\n");
		}


	}
	else{
		printf("usage: userTest GETGAIN,GETGAINSTOP\n");
	}


	return 1;
}

int cmd_UdpTest(int argc, char **argv)
{
	if( argc == 1 ){
		printf("argc:%d \n",argc);
		msg_pack_data_report2nd( &udp ,-1 ,0 );
	}
	if( argc < 2){ printf("argc error:%d \n",argc); return 0; }
	switch( argv[1][0] )
	{
			case '0':
				msg_pack_data_report2nd( &udp ,-1 ,2 );
				break;

			case '1':
				msg_pack_data_report2nd(&udp,-1,5);
				break;

			case '2':
				msg_pack_ip_rsp(&udp,-1);
				break;

			case '3':
				msg_pack_reset_rsp(&udp,-1);
				break;

			case '4':
				msg_pack_mac_rsp(&udp,-1);
				break;
			case '5':
				msg_pack_data_alarm(&udp,-1);
				break;

	}
	return 1;
}


int cmd_SetUser(int argc, char **argv)
{
	int data;
	if( argc >= 2){
		if( strcmp( argv[1], "PUT" ) == 0 )
		{
			if( argc < 3) {
				printf("argument missing! \n");
				return 0;
			}
			read_user_cfg_str(argv[2]);
			printf("Parsing...cmd_SetUser \n");
			write_user_cfg();
			write_ip_cfg();
		}
		else if( strcmp( argv[1], "GET" ) == 0 )
		{
			//printf("Output...cfg\n");
			make_user_cfg_str();
			printf("%s\n",buf_temp_usr_cfg);
			//TransmitMessage((unsigned char*)make_user_cfg_str(),PORT_CONTROL);
		}
		else if( strcmp( argv[1], "READ" ) == 0 )
		{
			read_user_cfg();
		}
		else if( strcmp( argv[1], "SIP" ) == 0 ) // server ip
		{
			if( argc == 3){
				strcpy( str_ip_server, argv[2] );
			}
			 printf("%s\n",str_ip_server);
		}
		else printf("not found(cmd)%s\n",argv[1]);

		return 1;
	}
	printf("try again:%d\n",argc);
	return 0;
}


int cmd_SelTp(int argc, char **argv)
{
	int data;
	if( argc > 1){
		data=strtoul(argv[1],NULL,0);
		data=min(15,data);
		data=max(0,data);
		Select1PPS_TP(data);
		printf("Select TP: %d\n",data);
	}
	else printf("try again\n");
	return 0;
}


int cmd_Nmea(int argc, char **argv)
{
	if( argc > 1)
		SendNmeaToF1000c(argv[1]);
	else printf("Try again \n");
	return 0;
}


int cmd_ResetRCV(int argc, char **argv)
{
	int v;
	i_cmd_ResetRCV=1;
	if( argc > 1){
		v = strtoul(argv[1],NULL,0);
		i_cmd_ResetRCVLimit = max(3, v ) ;
		i_cmd_ResetRCVLimit = min(60, v ) ;

	}
	else i_cmd_ResetRCVLimit = 3;

	printf("\n try Receiver reset:%d sec\n",i_cmd_ResetRCVLimit);
	return 0;
}

extern int bMonitorPHY;
int cmd_ResetPHY(int argc, char **argv)
{
	if( argc > 1 )
	{
		if(strcmp(argv[1],"HIGH")==0){
			printf("\n Reset PHY High always\n");
			AssertResetToPHYHigh();
		}
		if(strcmp(argv[1],"MONOFF")==0){
			bMonitorPHY = 0;
			printf("\n Monitor off\n");
		}
		if(strcmp(argv[1],"MONON")==0){
			bMonitorPHY = 1;
			printf("\n Monitor on\n");
		}
	}
	else{
		printf("\n Reset PHY \n");
		AssertResetToPHY();
	}
	return 0;
}

int cmd_PHY(int argc, char **argv)
{
	unsigned int offset;
	if( argc > 2 && strcmp(argv[1],"GET")==0 )
	{
		offset = strtoul(argv[2],NULL,0);
		printf("\nget: 0x%X: 0x%04X\n", offset, phy_get_regs(offset)&0xFFFF );
	}
	return 0;
}

int cmd_config(int argc, char **argv)
{
	unsigned int v;
	if( argc < 3){
		if( strcmp( argv[1], "KP" ) == 0 ){
                  printf("\n Kp Value = %f", Kp);
                }
                else if( strcmp( argv[1], "KI" ) == 0 ){
                           printf("\n Kp Value = %f", Ki);
                }

		printf("\n usage "
				"\n ex) config [Command] [Set Value, EX: 0/1/2  <-- 0:f1000c, 1:sync15 2:Ublox]"
				"\n" );
		return 0;
	}

   if( strcmp( argv[1], "KP" ) == 0 ){
           Kp= my_atof(argv[2]);
           printf("\n Set Kp Value = %f", Kp);
        }

   if( strcmp( argv[1], "KI" ) == 0 ){
           Ki= my_atof(argv[2]);
           printf("\n Set Ki Value = %f", Ki);
        }

	if( strcmp( argv[1], "RCVTYPE" ) == 0 ){
		v = strtoul(argv[2],NULL,0);
		if( v == 0)		printf("\n Set receiver type to 0 ( f1000c )");
		else if( v== 1) printf("\n Set receiver type to 1 ( Sync15 )");
		else if( v== 2) printf("\n Set receiver type to 2 ( Ublox )");
			else{  printf("\n Not valid argument\n"); return 0; }
		CONFIG.RcvType = (int)v;
		CONFIG.WriteEvent = ON;

		if (CONFIG.RcvType == 1) {
			set_tty(fdEB, B9600, 1);
			printf("Set Receiver type:Sync15\n");
		} else if (CONFIG.RcvType == 2) { // 1, 2
			set_tty(fdEB, B9600, 1);
			printf("Set Receiver type:Ublox\n");
		}	else {
			set_tty(fdEB, B115200, 1);
			printf("Set Receiver type:OEMV2\n");
			set_tty(fdEB2, B115200, 2);
			printf("Set Receiver type:OEMV1\n");
		}

	}
	if( strcmp( argv[1], "CVTYPE" ) == 0 ){
		v = strtoul(argv[2],NULL,0);
		if( v == 0)		printf("\n Set CV type to 0:Master");
		else if( v== 1) printf("\n Set CV type to 1:Slave");
		else{  printf("\n Not valid argument\n"); return 0; }
		CONFIG.iCVType = (int)v;
		CONFIG.WriteEvent = ON;

		if (CONFIG.iCVType == 1) {
			printf("Set Slave\n");
		} else
		{
			printf("Set Master\n");
		}
	}
	printf("\n");
	return 1;
}


int cmd_fpgar(int argc, char **argv)
{
	int addr;
	int data;
	if( argc > 1){
		addr=strtoul(argv[1],NULL,0);
		data=GetFpgaValue( addr );
		printf("get >>0x%02X( %d ) : 0x%02X( %d )\n",addr,addr,data,data);
	}
	else printf(" try again \n usage: fpgar addr\n");
	return 1;
}

int cmd_fpgaw(int argc, char **argv)
{
	int addr;
	int data;
	if( argc > 2){
		addr=strtoul(argv[1],NULL,0);
		data=strtoul(argv[2],NULL,0);
		SetFpgaValue( addr, data );
		printf("set>> 0x%02X( %d ) : 0x%02X( %d )\n",addr,addr,data,data);
	}
	else printf(" try again \n usage: fpgar addr\n");
	return 1;
}
int shift_str_left(char*s)
{
	do{
		*s = *(s+1);
		s++;
	}while(*s);
	return 0;
}

void trim_str(char *s)
{
	while( *s){
		if(*s==' ') shift_str_left(s);
		else break;
		s++;
	}
}
int parsing_command( char *s )
{
	int argc, cmdlp;
	int rlt = 0;

	upper_str(s);
	trim_str(s);
	//printf("\n%s",s);

	argc=0;
	if( strlen(s) > 0 ) argc = Parse_Args(s, argv);

	if( argc )
	{
		cmdlp = 0;

		while(cmdlp < MAX_CMD_NO && Cmds[cmdlp].func!=NULL )
		{
			if( strcmp( argv[0], Cmds[cmdlp].CmdStr ) == 0 )
			{
				Cmds[cmdlp].func( argc, argv );
				rlt = OK;
				//printf("Executing:%d,%s\n",cmdlp,Cmds[cmdlp].CmdStr);
				break;
			}
			cmdlp++;

		}

	}

	return rlt;

}



void PrintLogfile(char *filename)
{
	FILE *fp;
	char str[500];
	fp = fopen( filename ,"rt");
	if( !fp ){
		//printf("open error: %s\n",filename);
		return ;
	}

	while( (fgets(str,500,fp)) != NULL )
	{
		printf(str);
	}
	fclose(fp);
}

void DisplayHandler()
{
	DisplayLogHandler();
	TGainDisplay();
}

FILE *fpLogFile=NULL;
int bDisplayLog=0;
int iDisplayLogStep=0;
#define M_SIZE_TO_DISPLAY	1

void DisplayLogHandler()
{
	int i;
	char str[1000];
	if( !bDisplayLog ){
		iDisplayLogStep = 0;
		return ;
	}

	switch( iDisplayLogStep )
	{
		case 0:
			fpLogFile = fopen( "/gpsclock/log/GRCALogNew" ,"rt");
			if( !fpLogFile ){
				iDisplayLogStep = 2;
			}
			else{
				iDisplayLogStep = 1;
				dbg_printf("\n\n");
			}
			break;

		case 1:
			for( i=0; i<M_SIZE_TO_DISPLAY ; i++ )
			{
				if( fgets(str,500,fpLogFile) != NULL ){
					dbg_printf(str);
				}
				else{
					fclose(fpLogFile);
					iDisplayLogStep = 2;
				}
			}
			break;

		case 2:
			fpLogFile = fopen( "/log_tmp" ,"rt");
			if( !fpLogFile ){
				bDisplayLog = 0;
				dbg_printf("---end---\n");
			}
			else{
				iDisplayLogStep = 3;
				//printf("\n\n");
			}
			break;
		case 3:
			for( i=0; i<M_SIZE_TO_DISPLAY ; i++)
			{
				if( fgets(str,500,fpLogFile) != NULL )
					dbg_printf(str);
				else{
					fclose(fpLogFile);
					bDisplayLog = 0;
					dbg_printf("---end---\n");
				}
			}
			break;

	}

}

char dbg_string[1000+4];
void dbg_printf(char *fmt,...)
{
	va_list ap;
	int len;
	va_start(ap,fmt);
	len = vsnprintf(dbg_string,1000,fmt,ap);
	va_end(ap);
	TransmitMessage((BYTE*)dbg_string,PORT_CONTROL);
}



_stGetGain st_gg = {0,0,0,	0,0, 	0,0,0};
double 	prevRAW_DIFFERENCE=0, prevRAW_OFFSET=0;
#define M_st_gg_CNT 6
#define M_st_gg_SUM (120)
#define M_st_gg_THRES 0.3

void 	st_gg_SetDAC(int dac)
{
	CONTROL.ControlDAC = CONTROL.RealDAC = (double)dac;
	CONTROL.CurrentDAC = (unsigned short)(CONTROL.RealDAC);

	st_gg.cnt = 0;
	st_gg.diff_sum = 0; st_gg.ddiff_sum = 0;

}
void	GetOCXOGain()
{
	//RAW_DIFFERENCE
	//RAW_OFFSET
	if( !st_gg.running ) return;
	if( err_10m_cnt > 0 || holdover_time>0 || SYSTEM.EB.STATUS != EB_STATUS_RUN || fabs(st_gg.ddiff_sum)>10000){
		printf("error:Same value(%d) or Unlock(%d,%d) or ddif_sum>10,000(%d)\n",(int)RAW_OFFSET,holdover_time,(int)SYSTEM.EB.STATUS,(int)st_gg.ddiff_sum);
		st_gg.diff_sum = 0; st_gg.ddiff_sum = 0;
		st_gg.cnt = 0;
		return;
	}

	st_gg.ro = RAW_OFFSET;
	st_gg.diff = st_gg.ro - st_gg.ro_prev;
	st_gg.ddiff = st_gg.diff - st_gg.diff_prev;

	st_gg.diff_sum +=st_gg.diff;
	st_gg.ddiff_sum +=st_gg.ddiff;
	st_gg.cnt++;

	switch( st_gg.step )
	{
		case	0:
				USER.MANUAL_CONTROL = ON;
				st_gg_SetDAC(32000); st_gg.step = 1;
				break;

		case	1:
				if( st_gg.cnt > M_st_gg_CNT ){ st_gg.cnt = 0; st_gg.step++; st_gg.diff_sum = 0; st_gg.ddiff_sum = 0;}
				break;

		case	2:
				if( st_gg.cnt >= M_st_gg_SUM ){
					st_gg.diff_sol 	= st_gg.diff_sum	/(double)st_gg.cnt;
					st_gg.ddiff_sol = st_gg.ddiff_sum	/(double)st_gg.cnt;

					if( fabs(st_gg.ddiff_sol) < M_st_gg_THRES){
						printf("===========\n""1st Step Passed!:%6.2e,(,%6.2e,%d)\n",st_gg.ddiff_sol,st_gg.diff_sol,st_gg.cnt);
						st_gg_SetDAC(42000); st_gg.step = 3;

					}
					else { printf("===========\n""try Again:%6.2e\n",st_gg.ddiff_sol); st_gg_SetDAC(32000); st_gg.step = 1; }
				}
				break;

		case	3:
				if( st_gg.cnt > M_st_gg_CNT ){ st_gg.cnt = 0; st_gg.step++; st_gg.diff_sum = 0; st_gg.ddiff_sum = 0;}
				break;

		case	4:
				if( st_gg.cnt >= M_st_gg_SUM ){
					st_gg.diff_sol2nd 	= st_gg.diff_sum	/(double)st_gg.cnt;
					st_gg.ddiff_sol2nd  = st_gg.ddiff_sum	/(double)st_gg.cnt;

					if( fabs(st_gg.ddiff_sol2nd) < M_st_gg_THRES){
						printf("2nd Step Passed!:%6.2e,(,%6.2e,%d)\n",st_gg.ddiff_sol2nd,st_gg.diff_sol2nd,st_gg.cnt);
						st_gg.step = 0;
						st_gg.running = 0;
						st_gg.gain = (st_gg.diff_sol2nd - st_gg.diff_sol)/10000*1e-7;
						st_gg.center = 42000-(st_gg.diff_sol2nd*1e-7/st_gg.gain);

						CONFIG.GAIN = (float)st_gg.gain;
						CONFIG.DAC = (int)st_gg.center;
						CONFIG.WriteEvent = ON;
						USER.MANUAL_CONTROL = OFF;

						printf("---sol> gain,%.2e, center dac:%5d,......\n"
								,CONFIG.GAIN, (int)CONFIG.DAC
								);
						st_gg_SetDAC(CONFIG.DAC);
					}
					else { printf("===========\n""try Again2nd:%6.2e\n",st_gg.ddiff_sol2nd); st_gg_SetDAC(42000); st_gg.step = 3; }
				}
				break;


	}
	if(st_gg.running)
		printf(
				"getGain>step:%d,%3d), %5d"
				",dif,%+.2f, ddif,%+.2f, sum_d,%+6.2f, sum_dd,%+6.2f"
				",%.2f"
				"\n"
				,st_gg.step, st_gg.cnt,(int)CONTROL.CurrentDAC
				,st_gg.diff, st_gg.ddiff, st_gg.diff_sum, st_gg.ddiff_sum
				,st_gg.ro
		);

	st_gg.ro_prev = st_gg.ro;
	st_gg.diff_prev = st_gg.diff;

}
